<script setup>
import {getCurrentInstance, ref} from "vue"

import {GetShopCateList, GetCateInfo} from "@/api/shopCate.js"
const { proxy } = getCurrentInstance()

const keywords = ref("") // 搜索关键字
const activeIndex = ref(0); // 分类类型
const items = ref([]) // 分类数据
const itemInfo = ref([])

// 获取分类列表
const getCateList = async () => {
  try {
    const res = await GetShopCateList()
    if (res.data != null && res.data.length) {
      // 格式化数据
      items.value = res.data.map(item => {
        return {
          text: item.title,
          id: item.id
        }
      })

      // 查询分类下对应信息
      await getCateInfo(0)
    }
  } catch (e) {
  }
}

getCateList() // 调用分类


// 查询分类下对应信息
const getCateInfo = async (index) => {
  const result = await GetCateInfo({id: items.value[index].id})
  itemInfo.value = result.data
}

// 切换分类栏信息
const updateNav = (index) => {
  if (index == activeIndex.value) return
  getCateInfo(index)
}

// 进入商品列表页面
const enterCateList = (row) => {
  sessionStorage.setItem("cate-info",JSON.stringify(row))
  proxy.$router.push("/shopList")
}

</script>

<template>
  <div class="flex flex-col h-full">
    <van-nav-bar title="商品分类"/>
    <van-search v-model="keywords" placeholder="请输入搜索关键词"/>
    <div class="flex-1 py-[5px] px-[10px]">
      <van-tree-select
          v-model:main-active-index="activeIndex"
          height="100%"
          :items="items"
          @click-nav="updateNav"
      >
        <template #content>
         <div class="h-[300px] p-[5px]">
           <div class="cate-item">
             <div v-for="item in itemInfo" :key="item.id" @click="enterCateList(item)">
               <van-image :src="item.image" class="mb-[8px] w-full aspect-[1] rounded-[50%] overflow-hidden">
                 <template v-slot:loading>
                   <van-loading type="spinner" size="20" />
                 </template>
               </van-image>
               <div class="text-[12px] text-center w-full">{{ item.title }}</div>
             </div>
           </div>
         </div>
        </template>
      </van-tree-select>
    </div>
  </div>
</template>


<style scoped lang="scss">
.cate-item {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
}
</style>
